package com.yft.controller.login;

import com.yft.dao.base.BaseConstant;
import com.yft.entity.base.Order;
import com.yft.entity.base.OrderSort;
import com.yft.entity.competence.SysCompetence;
import com.yft.entity.login.SysMember;
import com.yft.enumeration.CompetenceType;
import com.yft.service.competence.SysCompetenceService;
import com.yft.service.login.SysMemberService;
import com.yft.util.MD5Encrypt;
import com.yft.util.ValidateCodeUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;


@Controller
public class YftCrmLoginController {
	private static final String controllerPath = "/yft/yftCrmLogin/";
	private static final String exceptControllerPath = "/auth/";
	private static final String loginViewPath = "/login/";
	private static final String mainViewPath = "/admin/main_page/jsp/";
	private static final String mainJsonPath = "/admin/main_page/jsp/json/";
	
	Logger log = Logger.getLogger(this.getClass());
	
	@Autowired(required = true)
	private SysMemberService sysMemberService;

	@Autowired(required = true)
	private SysCompetenceService sysCompetenceService;

//	@Autowired(required = true)
//	private SysCmRelationService sysCmRelationService;

	private boolean checkNullBlank(Object[] array){
		if(array==null || array.length==0){
			return false;
		}
		for(int i=0;i<array.length;i++){
			if(array[i] != null && !"".equals(((String)array[i]).trim())){
				continue;
			}else{
				return false;
			}
		}
		return true;
	}
	
	@RequestMapping(exceptControllerPath+"/login.html")
	public String loginView(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) throws Exception{
		return loginViewPath+"login";
	}
	/**
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(exceptControllerPath + "processLogin.html")
	public String memberLogin(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) throws Exception{
		boolean fleg = false;
		String loginID = request.getParameter("loginID");
		String password = request.getParameter("password");
		String codeValue = request.getParameter("codeValue");
		if(codeValue == null || "".equals(codeValue)){
			return null;
		}else{
			if ((loginID == null || loginID.equals("")) || (password == null || password.equals(""))) {
				return null;
			} else {
				String codeStr = (String)request.getSession().getAttribute("validateCode");
				if(codeStr == null || !codeValue.toLowerCase().equals(codeStr.toLowerCase())){
					model.addAttribute("error", "您输入的验证码错误!!");
				}else{
					loginID = loginID.trim();
					String loginIp  = request.getRemoteAddr();
					SysMember sysMember = sysMemberService.sysMemberLogin(loginID,password,loginIp);
					if (sysMember == null) {
						model.addAttribute("error", "用户不存在或密码不匹配!");
					} else {
						fleg = true;
						request.getSession().setAttribute(BaseConstant.SESSION_MEMBER, sysMember);
					}
				}
			}
		}
		model.addAttribute("success", fleg);
		return "message/messageJson";
	}

    /**
     * 获取下级菜单
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(controllerPath + "getNextMenus.html")
    public String getNextMenus(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
        SysMember sysMember = sysMemberService.currentMember(request);
        String upId = StringUtils.trimToEmpty(request.getParameter("sysComId"));
        String type = StringUtils.trimToEmpty(request.getParameter("type"));
        if(checkNullBlank(new Object[]{upId,type})){
            int typeInt = NumberUtils.toInt(type, -1);
            List<SysCompetence> sysCompetenceNextMenuList = new ArrayList<SysCompetence>();
            if(typeInt!=-1 && (typeInt == 2 || typeInt == 1)){
                List<CompetenceType> competenceTypeList = null;
                if(typeInt == 1){
                    competenceTypeList = new ArrayList<CompetenceType>();
                    competenceTypeList.add(CompetenceType.MENU);
                }else{
                    CompetenceType[] competenceTypes = CompetenceType.values();
                    competenceTypeList = new ArrayList<CompetenceType>(Arrays.asList(competenceTypes));
                    competenceTypeList.remove(CompetenceType.MENU);
                }
                Order order = new Order();
                order.addOrder("treePath",OrderSort.DESC);
                sysCompetenceNextMenuList = sysCompetenceService.getSysCompetenceList(new SysCompetence(),order,null);
                if(sysCompetenceNextMenuList!=null && !sysCompetenceNextMenuList.isEmpty()){
                    model.addAttribute("totalProperty",sysCompetenceNextMenuList.size());
                }else{
                    model.addAttribute("totalProperty",0);
                }
            }else{
                model.addAttribute("totalProperty",0);
            }
            model.addAttribute("sysCompetenceNextMenuList",sysCompetenceNextMenuList);
        }
        return mainJsonPath+"sysModeJson";
    }

	/**
	 * 跳至主面板
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */	
	@RequestMapping(controllerPath + "getMain.html")
	public String getMainContent(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
		SysMember sysMember = sysMemberService.currentMember(request);
		if(sysMember!=null){
			List<CompetenceType> competenceTypeList = new ArrayList<CompetenceType>();
			competenceTypeList.add(CompetenceType.MENU);
//			List<SysCompetence> sysCompetenceFirstMenuList = sysCmRelationService.getSysCompetenceListForSys(sysMember.getSysMemberId(), 0, 1, false, competenceTypeList);
			SysCompetence sysCompetence = new SysCompetence();
            sysCompetence.setcType(CompetenceType.MENU);
            Order order = new Order();
            order.addOrder("treePath",OrderSort.ASC);
            List<SysCompetence> sysCompetenceMenuList = sysCompetenceService.getSysCompetenceList(sysCompetence,order,null);
            model.addAttribute("sysCompetenceMenuList", sysCompetenceMenuList);
            boolean isHasMenuCompetence = true;
            if (sysCompetenceMenuList==null || sysCompetenceMenuList.isEmpty()){
                isHasMenuCompetence = false;
            }
            model.addAttribute("isHasMenuCompetence", isHasMenuCompetence);
			model.addAttribute("sysMember", sysMember);
			model.addAttribute("sysMemberId",sysMember.getSysMemberId());
			return mainViewPath+"main";
		}else{
			request.getSession().invalidate();
			return loginViewPath+"login";
		}
}
	/**
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */	
	@RequestMapping(exceptControllerPath + "sysMemberLoginout.html")
	public String getloginout(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		request.getSession().invalidate();
		return loginViewPath+"login";
	}


	/**
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(controllerPath + "updateSysMemberPassword.html")
	public String updateSysMemberPassword(HttpServletRequest request,HttpServletResponse response, ModelMap model) throws Exception {
		SysMember sysMember = (SysMember) sysMemberService.currentMember(request);
		if (sysMember == null) {
			return loginViewPath+"login";
		}
		SysMember temp = new SysMember();
		temp.setSysMemberId(sysMember.getSysMemberId());
		String password = request.getParameter("newPassword");
		String confirmPassword = request.getParameter("confirmPassword");
		String oldPassword = request.getParameter("oldPassword");
		boolean fleg =false;
		if(checkNullBlank(new Object[]{password,oldPassword,confirmPassword})){
			if(password.equals(confirmPassword)){
				if (sysMember.getPassword().equals(MD5Encrypt.EncodeAsHex(oldPassword))) {
					temp.setPassword(MD5Encrypt.EncodeAsHex(password));
					if(sysMemberService.updateValues(temp,null)){
						fleg=true;
						sysMember.setPassword(MD5Encrypt.EncodeAsHex(password));
						request.getSession().setAttribute(BaseConstant.SESSION_MEMBER,sysMember);
					}else{
						model.addAttribute("msg", "更新失败");
					}
				} else {
					model.addAttribute("msg", "旧密码输入错误，修改失败");
				}
			}else{
				model.addAttribute("msg", "新密码和确认密码不一致");
			}
			
			
		}else{
			model.addAttribute("msg", "信息不全，请补全");
		}
		model.addAttribute("success", fleg);
		return "message/messageJson";
	}	
	
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(exceptControllerPath + "createValidateCode.do")
	public String createValidateCode(HttpServletRequest request,HttpServletResponse response, ModelMap model) throws Exception {
		String str = ValidateCodeUtil.getValidateCode();
		request.getSession().setAttribute("validateCode", str);
		model.addAttribute("success", true);
		model.addAttribute("msg", str);
		return "message/messageJson";
	}
	
	/**
	 * 修正获得登陆验证码及登陆验证码图片
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(exceptControllerPath+"getValidateCode.html")
	public String validatecode(HttpServletRequest arg0,HttpServletResponse arg1) throws Exception {

		arg1.setHeader("Pragma", "No-cache");
		arg1.setHeader("Cache-Control", "no-cache");
		arg1.setDateHeader("Expires", 0);

		// 在内存中创建图象
		int w = 100, h = 25;
		BufferedImage image = new BufferedImage(w, h,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = image.createGraphics();

		// 设定背景色
		g2.setColor(Color.white);
		g2.fillRect(0, 0, w, h);

		// 随机产生6条干扰圈，使图象中的认证码不易被其它程序探测到
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			int x = random.nextInt(w);
			int y = random.nextInt(h);
			int xl = random.nextInt(50);
			int yl = random.nextInt(50);
			Ellipse2D e = new Ellipse2D.Double(x, y, xl ,yl ); 
			//使字符变圆滑
	        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
	        g2.setPaint(Color.gray);
	        g2.draw(e); 
		}

		// 画边框
		g2.setColor(new Color(127, 177, 212));
		g2.drawRect(0, 0, w-1 , h-1);
		
		// 设定字体
		AffineTransform at = new AffineTransform();
		AffineTransform fontAT = new AffineTransform();
		FontRenderContext frc = g2.getFontRenderContext();
		Font theFont = new Font("", Font.BOLD, 22);
		//设置起始位置
		at.setToTranslation(5, h / 1.3);
		
		// 产生随机高度 15至height之间
		float imght = 0;
		while (imght <= 15) {
			imght = Float.parseFloat(String.valueOf(random.nextInt(h)));
		}
		String str = (String)arg0.getSession().getAttribute("validateCode");
		
		Font theDerivedFont = theFont.deriveFont(fontAT);
		//调整字符间隔，做加空格操作
		StringBuffer str2=new StringBuffer();
		if(null !=str &&!"".equals(str)){
			for(int i=0;i<str.length();i++){
				str2.append(str.charAt(i)).append(" ");
			}
			TextLayout tstring2 = new TextLayout(str2.toString(), theDerivedFont, frc);
			Shape shape = tstring2.getOutline(at);
			g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
					RenderingHints.VALUE_ANTIALIAS_ON);
			g2.setClip(shape);
			g2.setColor(new Color(60, 161, 232));
			g2.fill(shape.getBounds());
			for (int j = shape.getBounds().y; j < shape.getBounds().y
			+ shape.getBounds().height; j = j + 3) {
				Line2D line = new Line2D.Float(0.0f, (float) j, (float) w,
						(float) j);
				g2.draw(line);
			}
			g2.dispose();
			// 输出图象到页面
			ImageIO.write(image, "JPEG", arg1.getOutputStream());
		}
		return null;
	}	
}
